import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:travel/model/hotel.dart';
import 'package:travel/routes/index.dart';
import 'package:travel/screen/flutter_screenutil.dart';
import 'package:travel/ui/scroll_refresh_config.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/radian.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';

/// 全部订单
class OrderAll extends StatefulWidget {
  final OrderTypeEnum orderType;

  const OrderAll({super.key, required this.orderType});

  @override
  State<OrderAll> createState() => _OrderAllState();
}

class _OrderAllState extends State<OrderAll> {
  RefreshController refreshController = RefreshController();

  List<HotelOrderModel> pageList = [];

  @override
  void initState() {
    initData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return scrollRefreshConfig(context);
  }

  @override
  void dispose() {
    refreshController.dispose();
    super.dispose();
  }

  void initData() {
    var r = Random.secure();

    pageList.add(HotelOrderModel(
        type: widget.orderType.value,
        name: '北海希尔顿欢朋酒店',
        address: '北海市海城区湖光中街甲六号',
        startDate: '11-25',
        endDate: '11-26',
        describe: '1晚1间',
        house: '江景大床房',
        status: HotelOrderStatusEnum.unpaid.value,
        price: r.nextInt(1000)));

    pageList.add(HotelOrderModel(
        type: widget.orderType.value,
        name: '北海希尔顿欢朋酒店',
        address: '北海市海城区湖光中街甲六号',
        startDate: '11-25',
        endDate: '11-26',
        describe: '1晚1间',
        house: '江景大床房',
        status: HotelOrderStatusEnum.unused.value,
        price: r.nextInt(1000)));

    pageList.add(HotelOrderModel(
        type: widget.orderType.value,
        name: '北海希尔顿欢朋酒店',
        address: '北海市海城区湖光中街甲六号',
        startDate: '11-25',
        endDate: '11-26',
        describe: '1晚1间',
        house: '江景大床房',
        status: HotelOrderStatusEnum.cancelled.value,
        price: r.nextInt(1000)));

    pageList.add(HotelOrderModel(
        type: widget.orderType.value,
        name: '北海希尔顿欢朋酒店',
        address: '北海市海城区湖光中街甲六号',
        startDate: '11-25',
        endDate: '11-26',
        describe: '1晚1间',
        house: '江景大床房',
        status: HotelOrderStatusEnum.cancelled.value,
        price: r.nextInt(1000)));

    pageList.add(HotelOrderModel(
        type: widget.orderType.value,
        name: '北海希尔顿欢朋酒店',
        address: '北海市海城区湖光中街甲六号',
        startDate: '11-25',
        endDate: '11-26',
        describe: '1晚1间',
        house: '江景大床房',
        status: HotelOrderStatusEnum.used.value,
        price: r.nextInt(1000)));
  }

  ScrollRefreshConfig scrollRefreshConfig(BuildContext context) {
    return ScrollRefreshConfig(
      refreshController: refreshController,
      onRefresh: onRefresh,
      onLoading: onLoading,
      child: listViewBuilder(context),
    );
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 35) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    setState(initData);

    /// 完毕
    refreshController.loadComplete();
  }

  ListView listViewBuilder(BuildContext context) {
    return ListView.builder(
      itemBuilder: (_, int index) {
        var row = pageList[index];
        return ToolsUtils.customGestureDetector(
            child: Container(
              margin: EdgeInsets.only(top: 10.h),
              alignment: Alignment.center,
              child: Container(
                width: 345.w,
                padding: EdgeInsets.all(10.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.w),
                  color: Colors.white,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Align(
                      alignment: Alignment.topLeft,
                      child: CircleAvatar(
                        radius: 12.5.w,
                        backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.color05b2),
                        child: ToolsUtils.assetImageSvg('u1647.svg', width: 13.w, height: 15.h),
                      ),
                    ),
                    Expanded(
                        child: Container(
                      padding: EdgeInsets.only(left: 10.w),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                widget.orderType.label,
                                style: StylesUtils.customTextStyle(
                                    fontSize: 17.sp,
                                    color: ColorsUtils.color0000,
                                    fontWeight: FontWeight.w700),
                              ),
                              Text.rich(TextSpan(children: getTextSpanByStatus(row.status)))
                            ],
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 15.h),
                            height: 25.h,
                            alignment: Alignment.centerLeft,
                            child: Text(
                              row.name,
                              style: StylesUtils.customTextStyle(
                                  fontSize: 16.sp, color: ColorsUtils.color0000),
                            ),
                          ),
                          Container(
                            height: 25.h,
                            alignment: Alignment.centerLeft,
                            child: Text(
                              row.address,
                              style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                            ),
                          ),
                          Container(
                            height: 25.h,
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '${row.startDate} 到 ${row.endDate}  •  ${row.describe}',
                              style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                            ),
                          ),
                          SizedBox(
                            height: 30.h,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  row.house,
                                  style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                                ),
                                Text.rich(TextSpan(children: [
                                  TextSpan(
                                      text: '￥',
                                      style: StylesUtils.customTextStyle(
                                          fontSize: 13.sp, color: ColorsUtils.colorD900)),
                                  TextSpan(
                                      text: '${row.price}',
                                      style: StylesUtils.customTextStyle(
                                          fontSize: 24.sp,
                                          fontWeight: FontWeight.w700,
                                          color: ColorsUtils.colorD900)),
                                ]))
                              ],
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 15.h),
                            alignment: Alignment.centerRight,
                            child: buildOrderStatusWidget(row),
                          )
                        ],
                      ),
                    ))
                  ],
                ),
              ),
            ),
            onTap: () {
              Get.toNamed(RoutePath.hotelOrderInfo, arguments: {'order': row});
            });
      },
      itemCount: pageList.length,
      itemExtent: 215.h,
    );
  }

  Widget? buildOrderStatusWidget(HotelOrderModel row) {
    if (row.status == HotelOrderStatusEnum.unpaid.value) {
      return Wrap(
        spacing: 10.w,
        alignment: WrapAlignment.end,
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          Container(
            constraints: BoxConstraints.expand(width: 80.h, height: 30.h),
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5.w),
                border:
                    Border.all(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorCccc))),
            child: TextButton(
                onPressed: () {},
                child: Text(
                  '取消',
                  style: StylesUtils.customTextStyle(fontSize: 13.sp, color: ColorsUtils.color3333),
                )),
          ),
          Container(
            constraints: BoxConstraints.expand(width: 80.h, height: 30.h),
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5.w),
                gradient: LinearGradient(
                    colors: [ColorsUtils.rgba(78, 115, 223, 1), ColorsUtils.rgba(8, 150, 227, 1)],
                    stops: const [0.0, 1.0],
                    transform: GradientRotation(RadianUtils.angleToRadian(180)))),
            child: TextButton(
                onPressed: () {
                  Get.toNamed(RoutePath.hotelOrderInfo, arguments: {'order': row});
                },
                child: Text(
                  '去支付',
                  style: StylesUtils.customTextStyle(fontSize: 13.sp),
                )),
          ),
        ],
      );
    }
    if (row.status == HotelOrderStatusEnum.unused.value) {
      return Container(
        constraints: BoxConstraints.expand(width: 80.h, height: 30.h),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(5.w),
            gradient: LinearGradient(
                colors: [ColorsUtils.rgba(78, 115, 223, 1), ColorsUtils.rgba(8, 150, 227, 1)],
                stops: const [0.0, 1.0],
                transform: GradientRotation(RadianUtils.angleToRadian(180)))),
        child: TextButton(
            onPressed: () {
              Get.toNamed(RoutePath.hotelOrderInfo, arguments: {'order': row});
            },
            child: Text(
              '去使用',
              style: StylesUtils.customTextStyle(fontSize: 13.sp),
            )),
      );
    }
    if (row.status == HotelOrderStatusEnum.cancelled.value ||
        row.status == HotelOrderStatusEnum.cancelled.value) {
      return Container(
        constraints: BoxConstraints.expand(width: 80.h, height: 30.h),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(5.w),
            border: Border.all(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorCccc))),
        child: TextButton(
            onPressed: () {
              Get.toNamed(RoutePath.hotelInfo);
            },
            child: Text(
              '再次预定',
              style: StylesUtils.customTextStyle(fontSize: 13.sp, color: ColorsUtils.color3333),
            )),
      );
    }
    return null;
  }

  List<InlineSpan> getTextSpanByStatus(int status) {
    List<InlineSpan> spans = [];
    spans.add(TextSpan(
      text: getStatusText(status),
      style: StylesUtils.customTextStyle(fontSize: 15.sp, color: getColor(status)),
    ));
    if (status == HotelOrderStatusEnum.used.value ||
        status == HotelOrderStatusEnum.cancelled.value) {
      spans.add(TextSpan(
        text: ' | ',
        style: StylesUtils.customTextStyle(color: ColorsUtils.colorCccc, fontSize: 15.sp),
      ));
      spans.add(WidgetSpan(child: ToolsUtils.assetImageSvg('u561.svg', width: 13.w, height: 15.h)));
    }
    return spans;
  }

  String getStatusText(int status) {
    for (var row in HotelOrderStatusEnum.values) {
      if (row.value == status) {
        return row.label;
      }
    }
    return '';
  }

  String getColor(int status) {
    for (var row in HotelOrderStatusEnum.values) {
      if (row.value == status) {
        return row.color;
      }
    }
    return '';
  }
}

/// 待付款
class OrderUnpaid extends StatefulWidget {
  final OrderTypeEnum orderType;

  const OrderUnpaid({super.key, required this.orderType});

  @override
  State<OrderUnpaid> createState() => _OrderUnpaidState();
}

class _OrderUnpaidState extends State<OrderUnpaid> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

/// 未使用
class OrderUnused extends StatefulWidget {
  final OrderTypeEnum orderType;

  const OrderUnused({super.key, required this.orderType});

  @override
  State<OrderUnused> createState() => _OrderUnusedState();
}

class _OrderUnusedState extends State<OrderUnused> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

/// 已取消
class OrderCancelled extends StatefulWidget {
  final OrderTypeEnum orderType;

  const OrderCancelled({super.key, required this.orderType});

  @override
  State<OrderCancelled> createState() => _OrderCancelledState();
}

class _OrderCancelledState extends State<OrderCancelled> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

/// 已使用
class OrderUsed extends StatefulWidget {
  final OrderTypeEnum orderType;

  const OrderUsed({super.key, required this.orderType});

  @override
  State<OrderUsed> createState() => _OrderUsedState();
}

class _OrderUsedState extends State<OrderUsed> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}
